package com.mogujie.tt.ui.activity;


import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.mogujie.tt.DB.sp.LoginSp;
import com.mogujie.tt.DB.sp.RegisterSp;
import com.mogujie.tt.R;
import com.mogujie.tt.config.RegisterConstant;
import com.mogujie.tt.customview.control.CustomDot;
import com.mogujie.tt.customview.control.PhoneVerificationCode;
import com.mogujie.tt.imservice.event.RegisterEvent;
import com.mogujie.tt.imservice.manager.IMRegisterManager;
import com.mogujie.tt.ui.base.TTBaseActivity;
import com.mogujie.tt.utils.FileUtil;
import com.mogujie.tt.utils.HttpUtilsApache;
import com.mogujie.tt.utils.ImageUtil;
import com.mogujie.tt.utils.JsonUtil;

import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;

import de.greenrobot.event.EventBus;

/**
 * Created by user on 2015/9/10.
 */

public class RegisterActivity extends TTBaseActivity  {
    private EditText mEditTextUserName;//输入11位手机号
    private EditText mEditTextUserPassword;//输入密码
    private EditText mEditTextConfirmPassword;//输入确认密码
    private EditText  mEditTextAuthCode;//输入验证码
    private PhoneVerificationCode mPhoneVerificationCode;//手机验证码


    private Button mRegisterButton;
    private LinearLayout mRegisterPage;
    private LinearLayout mDetailsPage;

    //详细信息
    private EditText mNickName;//昵称
    private ImageView mFace;//头像
    private EditText mMobilePhone;//手机
    private EditText mEmail;//邮箱
    private Button mCompleteDetails;//完成
    private TextView mTextViewSexSelection;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        boolean signUpPage;
        EventBus.getDefault().register(this);//注册EventBus

      //  setContentView(R.layout.tt_activity_register);
        LayoutInflater.from(this).inflate(R.layout.tt_activity_register,topContentView);
        initView();
        uiControlsOperation();
        signUpPage = this.getIntent().getExtras().getBoolean("signUpPage");
        if(signUpPage) {
            whichPageShown(true);//进入注册页面
        }else{
            whichPageShown(false);
            fromRegisigerJumpDetailUIcontrol();//初始化页面
        }

    }

    private void initView(){
        mEditTextUserName = (EditText)findViewById(R.id.user_name);

        mEditTextUserPassword = (EditText)findViewById(R.id.user_password);
        mEditTextConfirmPassword = (EditText)findViewById(R.id.confirm_password);

        mEditTextAuthCode = (EditText)findViewById(R.id.auth);//手机短信验证码

        mPhoneVerificationCode =(PhoneVerificationCode)findViewById(R.id.phoneverification);//手机验证码

        mRegisterButton =(Button)findViewById(R.id.register_in_button);
        mRegisterPage =(LinearLayout)findViewById(R.id.register_page);
        mDetailsPage = (LinearLayout)findViewById(R.id.details_page);


        //详细信息
        mNickName = (EditText)findViewById(R.id.nickname);
        mFace = (ImageView)findViewById(R.id.face);
        mMobilePhone = (EditText)findViewById(R.id.mobilephone);

        mEmail = (EditText)findViewById(R.id.set_email);
        mCompleteDetails = (Button)findViewById(R.id.completedetails);
        mTextViewSexSelection = (TextView)findViewById(R.id.sex_selection);

    }

    private void uiControlsOperation(){


        inputOperation(mEditTextUserName, findViewById(R.id.registered_users_line));
        inputOperation(mEditTextAuthCode, findViewById(R.id.auth_line));
        inputOperation(mEditTextUserPassword, findViewById(R.id.user_password_line));
        inputOperation(mEditTextConfirmPassword, findViewById(R.id.confirm_password_line));

        //详细信息
        inputOperation(mNickName, findViewById(R.id.nickname_line));
        inputOperation(mMobilePhone, findViewById(R.id.mobilephone_line));
        inputOperation(mEmail, findViewById(R.id.email_line));


        mPhoneVerificationCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mEditTextUserName.getText().toString().trim().length() > 0) {
                    IMRegisterManager.instance().whetherUserRegistered(mEditTextUserName.getText().toString().trim(), RegisterActivity.this, mPhoneVerificationCode);//请求验证用户时候注册

                } else {
                    Toast.makeText(RegisterActivity.this, "请输入正确的手机号码", Toast.LENGTH_LONG).show();
                }

            }
        });

        mRegisterButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                if (mEditTextUserName.getText().toString().trim().length() > 0) {
                    if (mEditTextAuthCode.getText().toString().trim().length() > 0) {
                        if (mEditTextUserPassword.getText().toString().trim().length() > 0 || mEditTextConfirmPassword.getText().toString().trim().length() > 0) {
                            IMRegisterManager.instance().passwordsConsistent(mEditTextUserPassword.getText().toString().trim(), mEditTextConfirmPassword.getText().toString().trim());//验证两次密码是否一致

                        } else {
                            Toast.makeText(RegisterActivity.this, "请输入正确的密码", Toast.LENGTH_LONG).show();
                        }
                    } else {
                        Toast.makeText(RegisterActivity.this, "请输入正确的验证码", Toast.LENGTH_LONG).show();
                    }

                } else {
                    Toast.makeText(RegisterActivity.this, "请输入正确的手机号码", Toast.LENGTH_LONG).show();
                }
            }
        });


        //详细信息
        mFace.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IMRegisterManager.instance().showDialog(RegisterActivity.this);
            }
        });

        mCompleteDetails.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mNickName.getText().toString().trim().length() > 0) {
                    if (mMobilePhone.getText().toString().trim().length() > 0) {
                        if (mEmail.getText().toString().trim().length() > 0) {
                            RegisterSp.instance().setdetailedNickNameStrConfig(mNickName.getText().toString().trim());
                            RegisterSp.instance().setdetailedMobilePhoneStrConfig(mMobilePhone.getText().toString().trim());
                            RegisterSp.instance().setdetailedEmailStrConfig(mEmail.getText().toString().trim());
                            IMRegisterManager.instance().submiUserDetails(RegisterActivity.this);
                        } else {
                            Toast.makeText(RegisterActivity.this, "请输入正确的邮箱", Toast.LENGTH_LONG).show();
                        }
                    } else {
                        Toast.makeText(RegisterActivity.this, "请输入正确的手机号码", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(RegisterActivity.this, "请输入正确的昵称", Toast.LENGTH_LONG).show();
                }

            }
        });

        mTextViewSexSelection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopupWindow(v);
            }
        });
    }

    /**
     * 输入焦点是否失去
     * @param mEditText
     * @param v
     */
    private void inputOperation(EditText mEditText,final View v){
        mEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View arg0, boolean arg1) {
                // TODO Auto-generated method stub
                //如果失去焦点
                if (arg1 == false) {
                    v.setBackgroundColor(Color.rgb(211,211,211));//灰色
                }
                //如果获得焦点
                else {
                    v.setBackgroundColor(Color.rgb(3,192,43));//青色
                }
            }
        });
    }

    /**
     * 显示顶部信息
     */
    private void showTopInformation(String test){
        if(test == null){
            return;
        }
        setTopBarDisplay();
        setCenterText(test);
    }

  /*  @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {


        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {

            return false;
        }
        return super.onKeyDown(keyCode, event);
    }*/

    @Override
    protected void onResume() {
        super.onResume();


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);//卸载注册事件

    }

    /**
     * ----------------------------event 事件驱动----------------------------
     */
    public void onEventMainThread(RegisterEvent.UserName event) {
        switch (event) {
            case USER_NAME_AVAILABLE:
                registeredUserSave();
                break;
            case USER_NAME_EXIST:
                break;
        }
    }

    public void onEventMainThread(RegisterEvent.UserPassWord event) {
        switch (event) {
            case USER_PASSWORD_SAME:
                registeredUserPassWordSave();
                break;
            case USER_PASSWORD_NO_SAME:
              Toast.makeText(RegisterActivity.this,"两次密码不一致，请修改!",Toast.LENGTH_LONG).show();
                break;
        }
    }

    public void onEventMainThread(RegisterEvent.AuthCode event) {
        switch (event) {
            case AUTH_CODE_SAME:
                registeredUserAuthCode();
                break;
            case AUTH_CODE_NO_SAME:

                break;
        }
    }
    /**
     * 注册用户名保存起来
     */
    private void registeredUserSave(){
        RegisterConstant.user_name =mEditTextUserName.getText().toString().trim();
    }
    /**
     * 注册用户密码保存起来
     */
    private void registeredUserPassWordSave(){
        RegisterConstant.user_password =mEditTextUserPassword.getText().toString().trim();//用户密码保存起来
        RegisterConstant.user_auth = mEditTextAuthCode.getText().toString().trim();//手机验证码保存起来
        RegisterConstant.user_name =mEditTextUserName.getText().toString().trim();//用户保存起来
        IMRegisterManager.instance().authCodeConsistent(RegisterActivity.this);//判断验证码
    }
    /**
     *  验证码一致表示注册成功可以退出
     */
    private void registeredUserAuthCode(){
        RegisterActivity.this.finish();
    }

    /**
     * 显示的是哪个页面
     * @param flag
     */
    private void whichPageShown(boolean flag){

        if(flag){
            mRegisterPage.setVisibility(View.VISIBLE);
            mDetailsPage.setVisibility(View.GONE);
            showTopInformation("注册用户");
        } else{
            mRegisterPage.setVisibility(View.GONE);
            mDetailsPage.setVisibility(View.VISIBLE);
            showTopInformation("个人信息");
        }
    }
    /**
     * 详细信息UI控件的初始化
     */
    private void fromRegisigerJumpDetailUIcontrol(){
        mNickName.setText(RegisterSp.instance().getSpDetailedInfo().getDetailedNickName().toString().trim());//设置昵称
        mEmail.setText(RegisterSp.instance().getSpDetailedInfo().getDetailedEmail().toString().trim());//设置邮箱
        mMobilePhone.setText(RegisterSp.instance().getSpDetailedInfo().getDetailedMobilePhone().toString().trim());//设置手机
        switch (RegisterSp.instance().getSpDetailedInfo().getDetailedSex()){  //设置选择男女控件默认选择
            case 0:mTextViewSexSelection.setText("保密");break;//保密
            case 1:mTextViewSexSelection.setText("男");break;//男
            case 2:mTextViewSexSelection.setText("女");break;//女
            default:break;
        }
        String path =RegisterConstant.PHOTO_PATH + RegisterConstant.IMAGE_FILE_TAILOR_NAME;
        File file = new File(path);
        if(file.exists()) {
            mFace.setImageBitmap(ImageUtil.getBigBitmapForDisplay(path, RegisterActivity.this));
        }else{
            mFace.setImageResource(R.drawable.tt_default_user_portrait_corner);
        }
//        Log.v("3333"," mNickName = "+RegisterSp.instance().getSpDetailedInfo().getDetailedNickName().toString().trim());
//        Log.v("3333"," mEmail = "+RegisterSp.instance().getSpDetailedInfo().getDetailedEmail().toString().trim());
//        Log.v("3333"," mMobilePhone = "+RegisterSp.instance().getSpDetailedInfo().getDetailedMobilePhone().toString().trim());
//        Log.v("3333"," Sex = "+RegisterSp.instance().getSpDetailedInfo().getDetailedSex());

    }

    /**
     * 选择性别
     * @param view
     */
    private void showPopupWindow(View view) {

        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(RegisterActivity.this).inflate(R.layout.pop_window, null);
        final PopupWindow popupWindow = new PopupWindow(contentView,ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        contentView.findViewById(R.id.textview1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                mTextViewSexSelection.setText("男");
                RegisterSp.instance().setdetailedSexIntConfig(1);
                popupWindow.dismiss();
            }
        });


        contentView.findViewById(R.id.textview2).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                mTextViewSexSelection.setText("女");
                RegisterSp.instance().setdetailedSexIntConfig(2);
                popupWindow.dismiss();
            }
        });


        contentView.findViewById(R.id.textview3).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                mTextViewSexSelection.setText("保密");
                RegisterSp.instance().setdetailedSexIntConfig(0);
                popupWindow.dismiss();
            }
        });
        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });
        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.selectmenu_bg_downward));
        // 设置好参数之后再show
//           popupWindow.showAsDropDown(view,0,0);
//        int[ ] location = new int[2];
//        Log.v("", "location[0] = " + location[0]);
//        Log.v("", "location[1] = " + location[1]);
//        Log.v("", "popupWindow.getWidth() = " + popupWindow.getWidth());
//        Log.v("","popupWindow.getHeight() = "+popupWindow.getHeight());
//        popupWindow.showAtLocation(view, Gravity.NO_GRAVITY, location[0],location[1]);
        //  popupWindow.showAtLocation(view, Gravity.CENTER, 0,0);
        WindowManager manager=(WindowManager) getSystemService(Context.WINDOW_SERVICE);
        //获取xoff
                int xpos=manager.getDefaultDisplay().getWidth()/2-popupWindow.getWidth();
      //  Log.v("","xpos = "+xpos);
        //xoff,yoff基于anchor的左下角进行偏移
        popupWindow.showAsDropDown(view, xpos/2, 0);
    }


    /**
     * 退出注册详细信息页面
     * @param view
     */
    public void onClickExit(View view){
        switch (view.getId()){
            case R.id.left_out_button:RegisterActivity.this.finish();break;
            default:break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 结果码不等于取消时候
        if (resultCode != RESULT_CANCELED) {

            switch (requestCode) {
                case RegisterConstant.IMAGE_REQUEST_CODE:
                    IMRegisterManager.instance().startPhotoZoom(data.getData(), RegisterActivity.this);
                    break;
                case RegisterConstant.CAMERA_REQUEST_CODE:
                    if (FileUtil.hasSdcard()) {
                        File tempFile = new File(
                              RegisterConstant.PHOTO_PATH
                                        + RegisterConstant.IMAGE_FILE_NAME);
                        IMRegisterManager.instance().startPhotoZoom(Uri.fromFile(tempFile), RegisterActivity.this);
                    } else {
                        Toast.makeText(RegisterActivity.this, "未找到存储卡，无法存储照片！",
                                Toast.LENGTH_LONG).show();
                    }

                    break;
                case RegisterConstant.RESULT_REQUEST_CODE:
                    if (data != null) {
                        IMRegisterManager.instance().getImageToView(data, RegisterActivity.this,mFace);
                    }
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

}
